public class OverrideCityMonthlyBudget
{
    public String msg{get;set;}
    public String IdSelect{get;set;}
    public Boolean DisplayApprove{get;set;}
    public Boolean DisplaySubmit{get;set;}
    public Boolean DisplaySave{get;set;}
    public Boolean DisplayReject{get;set;}
    public Boolean ForUpdate;
    Integer Inequality = 0;
    String CityHead;
    String SalesCity;    
    
    public CityBudget__c CityBudget{
         get{
             if(CityBudget== null)
                 CityBudget= new CityBudget__c();
             return CityBudget;
         }
         set;
    }  
    public CityMonthlyBudget__c CityMonthlyBudget{
         get{
             if(CityMonthlyBudget== null)
                 CityMonthlyBudget= new CityMonthlyBudget__c();
             return CityMonthlyBudget;
         }
         set;
    }        
    
    public Sub_Region_Budget__c SRB {
         get{
             if(SRB == null)
                 SRB = new Sub_Region_Budget__c();
             return SRB ;
         }
         set;
    }      
        
    public List<TableItemControl> TableItemsDown{         
        get{
             if(TableItemsDown== null)
                 TableItemsDown= new List<TableItemControl>();
             return TableItemsDown;
         }
        set;
    }    
    
    public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');     
        }  
        set;
    }
    public List<Sub_regional_Monthly_Budget__c> ExistSubregionalMB = [Select id,Month__c From Sub_regional_Monthly_Budget__c Where Sub_Region_Budget__c =: UrlId];
    public List<CityBudget__c> ExistRecord = new List<CityBudget__c>();
    public CityBudget__c SelectedRecord{
        get{        
             if(SelectedRecord== null)
                 SelectedRecord= new CityBudget__c();
             return SelectedRecord;
        }  
        set;
    }
    public List<Place__c> pList = new  List<Place__c>();  
    User cu  = [Select Name,UserRoleId,ProfileId,Title__c From User Where Id =:UserInfo.getUserId()];
    UserRole ur = [Select Id,Name,ParentRoleId  From UserRole Where Id =: cu.UserRoleId]; 
    Profile ProfileMarketing = [Select p.Name, p.Id From Profile p Where p.Name =: 'Medical Marketing'];
    Profile ProfileRSM = [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_M];
    Profile ProfileRSTM= [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_TM];
    Profile ProfileSRMMM = [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileSRMMM ];
                     
    public List<SelectOption> options{
        get{
            if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();

            options.add(new SelectOption(' ',' '));
            for(CityBudget__c c : ExistRecord)
            {
                options.add(new SelectOption(c.CityHead__c + ':' + c.SalesCity__c ,c.SalesCity__c));
            }

            return  options;
        }
        set;
    } 
    public PageReference actionSupport()
    {
        msg = null;
        ForUpdate = false;
        Double TotalSubRegion = 0;
        
        for(SelectOption s : options)
        {
            if(s.getValue() == IdSelect)
            {
                CityHead = s.getValue().split(':', 2)[0];
                SalesCity = s.getLabel();            
            }
        }
        
        if(ExistRecord.size() > 0 ){
            TableItemsDown.clear();

            Decimal TotalLastYearPEShipmentValue = 0;

            Decimal TotalLastYearPEConversionValue = 0;
            Decimal TotalThisYearPEConversionValue = 0;
            Decimal TotalLastYearInMarketSalesValue = 0;
            Decimal TotalThisYearInMarketSalesValue = 0;


            List<AggregateResult> TotalLastYearInMarketSales = [Select sum(InMarketSaleskg__c)InMarketSales, Month__c Mon From 
               InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: integer.valueof(SRB.Year__c)-1 and SalesCity__c =: SalesCity group by Month__c]; 
            List<AggregateResult> TotalThisYearInMarketSales = [Select sum(InMarketSalesForcast__c)InMarketSales, Month__c Mon From 
               InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: integer.valueof(SRB.Year__c)  and SalesCity__c =: SalesCity group by Month__c];                 
        
            List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)kg,Month__c Mon From Shipment__c Where KG__c > 0 and   Year__c =: integer.valueof(SRB.Year__c)-1 and SalesCity__c =: SalesCity group by Month__c];
  
            List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn,Month__c Mon  From 
                                          Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(integer.valueof(SRB.Year__c)-1) and Sales_city__c =: SalesCity group by Month__c];
            
            List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                          Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: SRB.Year__c and Sales_city__c =: SalesCity group by Month__c];
                   
            List<AggregateResult> SubRegionMonthlyBud = [Select sum(Budget_KG__c) Kg,Month__c Mon, id Ids From Sub_regional_Monthly_Budget__c Where Sub_Region_Budget__c =: UrlId group by Month__c,id];
            
            
            
            for(Integer i = 1, j = 0; i < 13;i++)
            {
                TableItemControl T = new TableItemControl();
                T.Str = String.valueof(i);
                
                Decimal LastYearPEShipmentValue = 0;

                Decimal SubRegionLastYearInMarketSalesValue = 0;
                Decimal SubRegionThisYearInMarketSalesValue = 0;                
                Decimal LastYearPEConversionValue = 0;
                Decimal ThisYearPEConversionValue = 0;
                for(AggregateResult ag : TotalLastYearInMarketSales)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        SubRegionLastYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                    }
                }                
                for(AggregateResult ag : TotalThisYearInMarketSales)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        SubRegionThisYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                    }
                }  
                for(AggregateResult ag : TotalLastYearPEShipment)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        LastYearPEShipmentValue = (Decimal)ag.get('kg');
                    }
                }  
 
                for(AggregateResult ag : SubRegionLastYearPEConversion)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        LastYearPEConversionValue = (Decimal)ag.get('TotalIn');
                    }
                }                                                  
                for(AggregateResult ag : SubRegionThisYearPEConversion)
                {
                    if(Integer.valueof(ag.get('Mon'))== i)
                    {
                        ThisYearPEConversionValue = (Decimal)ag.get('TotalIn');
                    }
                }
                
                TotalLastYearPEShipmentValue += LastYearPEShipmentValue;

                TotalLastYearPEConversionValue += LastYearPEConversionValue;
                TotalThisYearPEConversionValue += ThisYearPEConversionValue;
                TotalLastYearInMarketSalesValue += SubRegionLastYearInMarketSalesValue;
                TotalThisYearInMarketSalesValue += SubRegionThisYearInMarketSalesValue;                
                
                if(LastYearPEShipmentValue > 0)
                    T.CMB.LastYearInMarketSaleskg__c= SubRegionLastYearInMarketSalesValue / LastYearPEShipmentValue;
                else
                    T.CMB.LastYearInMarketSaleskg__c = 0;
                if(LastYearPEConversionValue > 0)   
                    T.CMB.LastYearPESamplekg__c = LastYearPEShipmentValue / LastYearPEConversionValue;
                else
                    T.CMB.LastYearPESamplekg__c = 0;

                T.CMB.ThisYearInMarketSalesKg__c = 0;
                T.CMB.ThisYearPESampleKg__c = 0;
                T.CMB.ConversionForcast__c = ThisYearPEConversionValue;
                T.CMB.InMarketValueHide__c = SubRegionThisYearInMarketSalesValue;
                
                for(AggregateResult agR : SubRegionMonthlyBud)
                {
                    if(Integer.valueof(agR.get('Mon'))== i)
                    {
                        List<AggregateResult> TotalCityMonBud = [Select sum(BudgetKg__c) Kg  From CityMonthlyBudget__c Where SubRegionalMonthlyBudget__c =: string.valueof(agR.get('Ids')) ];
                        if(TotalCityMonBud.size() > 0){
                             T.MonbudSurplus = 1000;
                        /*
                            if(TotalCityMonBud[0].get('Kg') != null)
                                T.MonbudSurplus = (Double)agR.get('Kg') - (Double)TotalCityMonBud[0].get('Kg');
                            else
                                T.MonbudSurplus = (Double)agR.get('Kg');
                        */        
                        }
                        else
                           // T.MonbudSurplus = (Double)agR.get('Kg');
                           T.MonbudSurplus = 1000;
                        TotalSubRegion += T.MonbudSurplus;    
                    }
                }                   
                                 
                TableItemsDown.add(T);
            }

            
           List<CityBudget__c> SelectedRecordList = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, 
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
                c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c,  c.InMarketValueHide__c ,c.ConversionForcast__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.CityHead__c,c.BudgetIsChanged__c,
                c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
                c.Name =: SRB.Year__c +'年'+ SalesCity + '专业样品管理' and 
                c.CityHead__c =: CityHead and c.SubRegionBudget__c =: UrlId ];  //
                
                                
            if(SelectedRecordList.size() > 0){
                
                SelectedRecord = SelectedRecordList[0];
                CityMonthlyBudget.BudgetKg__c = SelectedRecord.TotalBudgetkg__c;
                CityMonthlyBudget.BudgetRMB__c = SelectedRecord.TotalBudgetRMB__c;
                
                List<CityMonthlyBudget__c> existMonBud = [Select c.Year__c, c.ThisYearPESampleKg__c,  c.InMarketValueHide__c ,c.ConversionForcast__c,
                    c.ThisYearInMarketSalesKg__c, c.SystemModstamp, c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c,
                    c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
                    c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c =: SelectedRecord.id and RecordType__c =:'Budget'];
               
                if(existMonBud.size() > 0){
                    ForUpdate = true;
                    TotalSubRegion = 0;
                    for(CityMonthlyBudget__c sr : existMonBud)
                    {
                        for(TableItemControl t1 : TableItemsDown)
                        {
                            if( sr.Month__c == t1.str)
                            { 
                                t1.CMB = sr;
                                t1.MonbudSurplus = 1000;
                         /*
                                if(t1.MonbudSurplus > 0)
                                    t1.MonbudSurplus += sr.BudgetKg__c;
                                else
                                    t1.MonbudSurplus = sr.BudgetKg__c;
                         */           
                                TotalSubRegion += t1.MonbudSurplus;
                            }
                        }
                    }
                }     
            }
            TableItemControl TT = new TableItemControl();
            TT.Str = '总计';
            if(TotalLastYearPEShipmentValue > 0) 
                TT.CMB.LastYearInMarketSaleskg__c = TotalLastYearInMarketSalesValue / TotalLastYearPEShipmentValue ;
            else
                TT.CMB.LastYearInMarketSaleskg__c = 0;
            if(TotalLastYearPEConversionValue > 0) 
                TT.CMB.LastYearPESamplekg__c = TotalLastYearPEShipmentValue / TotalLastYearPEConversionValue ;
            else
                TT.CMB.LastYearPESamplekg__c = 0;
                
            TT.CMB.ThisYearInMarketSalesKg__c = 0;
            TT.CMB.ThisYearPESampleKg__c = 0;
            TT.CMB.ConversionForcast__c = TotalThisYearPEConversionValue ;
            TT.CMB.InMarketValueHide__c = TotalThisYearInMarketSalesValue ; 
            
                       
            TT.MonbudSurplus = TotalSubRegion;
            TableItemsDown.add(TT);            
            
                       
         }          

        return null;
    } 
    public OverrideCityMonthlyBudget(){    

        DisplaySubmit = true;
        DisplayApprove = false;  
        DisplaySave = true;
        DisplayReject = false;
        SRB = [Select s.total_score__c, s.potential_score__c, s.final_weighting__c, s.Year__c, s.Total_budget_kg__c, 
            s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, s.This_year_In_market_sales_kg__c, 
            s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, s.Rate__c, s.Place__c, s.PE_Sample_Management__c, 
            s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c, s.Last_year_conversion_weighting__c, s.ApprovalStatus__c,
            s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c,s.Id, s.Area__c, s.ApprovedFormula__c ,s.ApprovalStatusFormula__c 
            From Sub_Region_Budget__c s Where s.id =: UrlId];
                    
       if(SRB.ApprovalStatusFormula__c != '审批通过' ) 
       {
           msg = '样品管理未通过审批！';
           DisplaySubmit = false;
           DisplayApprove = false;  
       }
       else
       {  
            ExistRecord = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, c.InMarketValueHide__c ,c.ConversionForcast__c,
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
                c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, 
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c, c.CityHead__c, 
                c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Submit__c,c.Changed__c  From CityBudget__c c Where 
                c.SubRegionBudget__c =: UrlId];
            if(ExistRecord.size()<= 0)
            {
                msg = '您还未对城市样品进行未分配！';
                DisplaySubmit = false;
                DisplayApprove = false;              
            }
            else
            {
               if(ExistRecord[0].Approved__c == true)
               {
                    msg = '审批通过，不能再修改！';
                    DisplaySave = false;
                    DisplaySubmit = false;
                    DisplayApprove = false;                   
               }
               else{
                   if((cu.ProfileId == ProfileRSM.id)||(cu.ProfileId == ProfileRSTM.id)){
                        DisplaySubmit = false;
                        DisplaySave = false;
                        DisplayApprove = true;  
                        DisplayReject = true;
                                        
                   }
                   if((cu.ProfileId ==ProfileSRMMM.id)||(cu.ProfileId == ProfileMarketing.id)){
                        if(ExistRecord[0].Submit__c){ 
                            msg = '已提交申请，不能再修改！';
                            DisplaySave = false;
                            DisplaySubmit = false;
                            DisplayApprove = false;                  
                        }
                   } 
                   if((cu.ProfileId == ProfileRSM.id)||(cu.ProfileId == ProfileRSTM.id)){
                       if(!ExistRecord[0].Submit__c){
                            msg = '未提交审批';
                            DisplaySubmit = false;
                            DisplaySave = false;
                            DisplayApprove = false;  
                            DisplayReject = false;
                             
                       }
                   } 
              }              
            }
        }
    }

    public void SetRecord(Boolean Submit)
    {
        // set table items up
        List<CityMonthlyBudget__c> CityBudgetMonBudgetList = new List<CityMonthlyBudget__c>();
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '总计')
            {
                continue;
            }

            t.CMB.Name = SRB.Year__c + '年' + SalesCity + t.str + '月专业样品管理';
            t.CMB.Month__c = t.str;
            if(t.CMB.BudgetKg__c == null)
                t.CMB.BudgetKg__c = 0;
            t.CMB.BudgetRMB__c = t.CMB.BudgetKg__c * SelectedRecord.Rate__c;
            if(t.CMB.BudgetKg__c > 0)
                t.CMB.ThisYearInMarketSalesKg__c = t.CMB.InMarketValueHide__c / t.CMB.BudgetKg__c;
            else
                t.CMB.ThisYearInMarketSalesKg__c = 0;
            t.CMB.ThisYearInMarketSalesKg__c = t.CMB.ThisYearInMarketSalesKg__c.intValue();
            if(t.CMB.ConversionForcast__c > 0)
                t.CMB.ThisYearPESampleKg__c = t.CMB.BudgetKg__c / t.CMB.ConversionForcast__c;
            else
                t.CMB.ThisYearPESampleKg__c = 0;
            t.CMB.ThisYearPESampleKg__c = t.CMB.ThisYearPESampleKg__c.intValue(); 
             
            for(Sub_regional_Monthly_Budget__c s :ExistSubregionalMB )
            {
                if(t.CMB.Month__c == s.Month__c)
                {
                    t.CMB.SubRegionalMonthlyBudget__c = s.id;
                }
            }            
            
            if(!ForUpdate){
                t.CMB.CityBudget__c = SelectedRecord.id;
            }
                
            CityBudgetMonBudgetList.add(t.CMB);
        }
        if((IdSelect != ' ') && (IdSelect != ' '))
        {
            if(ForUpdate)
            {
                if(CityBudgetMonBudgetList.size()>0)
                    update CityBudgetMonBudgetList;
            }
                
            else{
                if(CityBudgetMonBudgetList.size()>0)
                {
                    insert CityBudgetMonBudgetList; 
                    ForUpdate = true;
                }  
            }
            
        }
    }

    public PageReference Save()
    {
        try{
            if(SRB.ApprovalStatusFormula__c != '审批通过')
            {   
                return null;
            }
    
            Decimal AllocatedNum = decimal.valueof(0);     
            
            for(TableItemControl t : TableItemsDown){
                if(T.Str == '总计')
                {
                    continue;
                }
                if((t.CMB.BudgetKg__c != null)&&(t.CMB.BudgetKg__c > 0)){
                    if((AllocatedNum == null)||(AllocatedNum == 0))
                        AllocatedNum = t.CMB.BudgetKg__c;
                    else
                        AllocatedNum += t.CMB.BudgetKg__c;
                }    
            }
         
            if(AllocatedNum != SelectedRecord.TotalBudgetkg__c)
            {
                //msg = '分配公斤数应等于分配到城市的预算公斤数'; fix by scao
                List<CityMonthlyBudget__c> errorCityMonthlyBudget = [Select c.Year__c, c.ThisYearPESampleKg__c,  c.InMarketValueHide__c ,c.ConversionForcast__c,
                    c.ThisYearInMarketSalesKg__c, c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c,
                    c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
                    c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c =: SelectedRecord.id and RecordType__c =:'Budget'];
                if(errorCityMonthlyBudget.size() > 0)
                    delete errorCityMonthlyBudget;
            } 
      
            SetRecord(false);  
            msg = null;    
            return null;
        }
        catch (DmlException e) {
            ApexPages.addMessages(e);
            return null;
        }
    }

    public PageReference Submit()
    {
        List<CityBudget__c> SubmitSRBL = new List<CityBudget__c>();     
        
        for(CityBudget__c cb : ExistRecord)
        {
           List<CityBudget__c> SubmitSRB = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, 
                    c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
                    c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, 
                    c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                    c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.RSM__r.email,
                    c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where c.CityHead__c =: cb.CityHead__c and 
                    c.name =: SRB.Year__c +'年' + cb.SalesCity__c + '专业样品管理' and c.SubRegionBudget__c =: UrlId];             
           if(SubmitSRB.size() > 0)
               SubmitSRBL.add(SubmitSRB[0]);
        }
        for(CityBudget__c s : SubmitSRBL)
        {
            if(s.Changed__c == Inequality)
            {
                msg = s.name + '预算没分配完';
                return null;
            }
        }
        String emailAddresses;
        String subRegion;           
        for(CityBudget__c  s : SubmitSRBL)
        {
            s.Submit__c = true;
            emailAddresses = s.RSM__r.email;
            subRegion = s.SubRegion__c;
        }
        update SubmitSRBL;
        
        List<String> toAddresses = new List<String>();
        toAddresses.add( emailAddresses );  
        List<String> ccAddresses = new List<String>();
        String Body = '您好！\n' +  '您收到一个新的' + subRegion + '专业样品管理申请!\n' + string.valueof(Date.Today());
        String Subject = subRegion + '申请';
                
        EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);        

        try{
               string SubRegionName = SRB.name.substring(SRB.name.indexOf('年')+1,SRB.name.indexOf('专'));
                List<AggregateResult> TotalLastYearInMarketSales = [Select sum(InMarketSaleskg__c)InMarketSales, Month__c Mon From 
                   InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: Integer.valueof(SRB.Year__c)-1  and SubRegion__c =: SubRegionName group by Month__c]; 
    
                List<AggregateResult> TotalThisYearInMarketSales = [Select sum(InMarketSalesForcast__c)InMarketSales, Month__c Mon From 
                   InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: Integer.valueof(SRB.Year__c) and SubRegion__c =: SubRegionName group by Month__c];                 
    
                List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)kg,Month__c Mon From Shipment__c Where KG__c > 0 and   Year__c =: Integer.valueof(SRB.Year__c)-1 and SubRegion__c =: SubRegionName group by Month__c];
    
                List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn,Month__c Mon  From 
                                              Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(Integer.valueof(SRB.Year__c)-1) and subregion__c =: SubRegionName group by Month__c];
                
                List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                              Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: SRB.Year__c and subregion__c =: SubRegionName group by Month__c];
    
                Decimal TotalLastYearPEShipmentValue = 0;
    
                Decimal TotalLastYearPEConversionValue = 0;
                Decimal TotalThisYearPEConversionValue = 0;
                Decimal TotalLastYearInMarketSalesValue = 0;
                Decimal TotalThisYearInMarketSalesValue = 0;
                List<Sub_regional_Monthly_Budget__c> InsertSubMonBudget = new List<Sub_regional_Monthly_Budget__c>();
                Integer num;
                for(num = 1;num < 13;num++)
                {
                    Sub_regional_Monthly_Budget__c InsertSubMonItem = [Select s.Year__c, s.This_year_PE_Sample_kg__c,
                         s.This_year_In_market_sales_kg__c, s.Sub_Region_Budget__c, s.Rate__c, s.Name,
                         s.Month__c, s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c, 
                         s.InMarketValueHide__c, s.Id,  s.ConversionForcast__c, s.Budget_RMB__c, s.Budget_KG__c 
                         From Sub_regional_Monthly_Budget__c s Where s.Sub_Region_Budget__c =: SRB.id and s.Month__c =: string.valueof(num)];
                    List<AggregateResult> SubRegionThisMonthKg = [Select sum(BudgetKg__c) kg From CityMonthlyBudget__c Where Month__c =: string.valueof(num) and SubRegionBudget__c =: string.valueof(SRB.id).substring(0,15)];

                    if(SubRegionThisMonthKg.size() > 0)
                        InsertSubMonItem.Budget_KG__c = Integer.valueof(SubRegionThisMonthKg[0].get('kg'));
                    else
                        InsertSubMonItem.Budget_KG__c = 0;
                    if(InsertSubMonItem.Budget_KG__c != null)
                        InsertSubMonItem.Budget_RMB__c = InsertSubMonItem.Budget_KG__c * SRB.Rate__c;
                
                    Decimal LastYearPEShipmentValue = 0;
                    Decimal SubRegionLastYearInMarketSalesValue = 0;
                    Decimal SubRegionThisYearInMarketSalesValue = 0;                
                    Decimal LastYearPEConversionValue = 0;
                    Decimal ThisYearPEConversionValue = 0;
                    for(AggregateResult ag : TotalLastYearInMarketSales)
                    {
                        if(Integer.valueof(ag.get('Mon'))== num)
                        {
                            SubRegionLastYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                        }
                    }                
                    for(AggregateResult ag : TotalThisYearInMarketSales)
                    {
                        if(Integer.valueof(ag.get('Mon'))== num)
                        {
                            SubRegionThisYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                        }
                    }  
                    for(AggregateResult ag : TotalLastYearPEShipment)
                    {
                        if(Integer.valueof(ag.get('Mon'))== num)
                        {
                            LastYearPEShipmentValue = (Decimal)ag.get('kg');
                        }
                    }   
                 
                    for(AggregateResult ag : SubRegionLastYearPEConversion)
                    {
                        if(Integer.valueof(ag.get('Mon'))== num)
                        {
                            LastYearPEConversionValue = (Decimal)ag.get('TotalIn');
                        }
                    }                                                  
                    for(AggregateResult ag : SubRegionThisYearPEConversion)
                    {
                        if(Integer.valueof(ag.get('Mon'))== num)
                        {
                            ThisYearPEConversionValue = (Decimal)ag.get('TotalIn');
                        }
                    }
    
                    TotalLastYearPEShipmentValue += LastYearPEShipmentValue;
                    TotalLastYearPEConversionValue += LastYearPEConversionValue;
                    TotalThisYearPEConversionValue += ThisYearPEConversionValue;
                    TotalLastYearInMarketSalesValue += SubRegionLastYearInMarketSalesValue;
                    TotalThisYearInMarketSalesValue += SubRegionThisYearInMarketSalesValue;
                    
                    InsertSubMonItem.ConversionForcast__c = ThisYearPEConversionValue;
                    InsertSubMonItem.InMarketValueHide__c = SubRegionThisYearInMarketSalesValue;
                    
                    if(LastYearPEShipmentValue > 0)
                        InsertSubMonItem.Last_year_In_market_sales_kg__c= SubRegionLastYearInMarketSalesValue / LastYearPEShipmentValue;
                    else
                        InsertSubMonItem.Last_year_In_market_sales_kg__c = 0;
                    if(LastYearPEConversionValue > 0)   
                        InsertSubMonItem.Last_year_PE_Sample_kg__c = LastYearPEShipmentValue / LastYearPEConversionValue;
                    else
                        InsertSubMonItem.Last_year_PE_Sample_kg__c = 0;  

                    if(InsertSubMonItem.Budget_KG__c > 0)
                        InsertSubMonItem.This_year_In_market_sales_kg__c= InsertSubMonItem.InMarketValueHide__c / InsertSubMonItem.Budget_KG__c;
                    else
                        InsertSubMonItem.This_year_In_market_sales_kg__c = 0;
                    if((InsertSubMonItem.ConversionForcast__c > 0) &&(InsertSubMonItem.Budget_KG__c > 0))  
                        InsertSubMonItem.This_year_PE_Sample_kg__c = InsertSubMonItem.Budget_KG__c / InsertSubMonItem.ConversionForcast__c;
                    else
                        InsertSubMonItem.This_year_PE_Sample_kg__c = 0;
                
                    InsertSubMonBudget.add(InsertSubMonItem);
                }
            update InsertSubMonBudget;
            
            SRB.ApprovalStatus__c = '等待片区经理审批';
            update SRB;
        }
        catch (DmlException e) {
            ApexPages.addMessages(e);
            return null;
         } 

    
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
            
    public PageReference Cancel()
    {
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
    
    public PageReference Reject()
    {        
        List<CityBudget__c> SubmitSRBL = new List<CityBudget__c>();
        String ownerIds;
        String subRegion;
        for(CityBudget__c cb : ExistRecord)
        {
           List<CityBudget__c> SubmitSRB = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, 
                    c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
                    c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, 
                    c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                    c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.RSM__r.email,
                    c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where c.CityHead__c =: cb.CityHead__c and 
                    c.name =: SRB.Year__c +'年' + cb.SalesCity__c + '专业样品管理' and c.SubRegionBudget__c =: UrlId];             
           
           if(SubmitSRB.size() > 0)
           {
               SubmitSRBL.add(SubmitSRB[0]);
               ownerIds = SubmitSRB[0].OwnerId;
               subRegion = SubmitSRB[0].SubRegion__c;
           }
        }
    
        for(CityBudget__c  s : SubmitSRBL)
        {
            s.Approved__c = false;
            s.Submit__c = false;
        }
        update SubmitSRBL;

        SRB.ApprovalStatus__c = '审批驳回';
        update SRB;
        
        User RMMM_Info = [Select email From User Where id =: ownerIds ];
        String emailAddresses = RMMM_Info.email;
        
        List<String> toAddresses = new List<String>();
        toAddresses.add( emailAddresses );  
        List<String> ccAddresses = new List<String>();
        String Body = '您好！\n' +  + '您的' + subRegion + '专业样品管理申请,被驳回！!\n' + string.valueof(Date.Today());
        String Subject = subRegion + '申请驳回';
                
        EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);     
     
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }    
    
    
    public PageReference Approve()
    {        
        List<CityBudget__c> SubmitSRBL = new List<CityBudget__c>();
        String ownerIds;
        String subRegion;
        for(CityBudget__c cb : ExistRecord)
        {
           List<CityBudget__c> SubmitSRB = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, 
                    c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
                    c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, 
                    c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                    c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.RSM__r.email,
                    c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where c.CityHead__c =: cb.CityHead__c and 
                    c.name =: SRB.Year__c +'年' + cb.SalesCity__c + '专业样品管理' and c.SubRegionBudget__c =: UrlId];             
           if(SubmitSRB.size() > 0)
           {
               SubmitSRBL.add(SubmitSRB[0]);
               ownerIds = SubmitSRB[0].OwnerId;
               subRegion = SubmitSRB[0].SubRegion__c;           
           }
               
        }
        for(CityBudget__c s : SubmitSRBL)
        {
            if(s.Changed__c == Inequality)
            {
                msg = s.name + '预算没分配完';
                return null;
            }
        }        
        for(CityBudget__c  s : SubmitSRBL)
        {
            s.Approved__c = true;
        }
        update SubmitSRBL;

        SRB.ApprovalStatus__c = '审批通过';
        update SRB;

        User RMMM_Info = [Select email From User Where id =: ownerIds ];
        String emailAddresses = RMMM_Info.email;
        
        List<String> toAddresses = new List<String>();
        toAddresses.add( emailAddresses );  
        List<String> ccAddresses = new List<String>();
        String Body = '您好！\n' +  + '您的' + subRegion + '专业样品管理申请,审批通过！!\n' + string.valueof(Date.Today());
        String Subject = subRegion + '样品管理审批通过';
                
        EmailFunction.SendEmail(toAddresses, ccAddresses, Body, Subject);   


            
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
    
    
    static testMethod void OverrideViewTest()
    {
       Profile p  = [select id from profile where name =: GlobalProperties.ProfileRMMM  ];
        UserRole SRMMM_SOC = [Select Id,Name From UserRole Where Name =: GlobalProperties.SRMMM_SOC];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8',UserRoleId = SRMMM_SOC.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='asdfdaa@testorg1.com');
        insert u1;
        
        System.runAs(u1) {
            PE_Sample_Management__c PE = new PE_Sample_Management__c();
            PE.WOC_Total_budget_RMB__c = 1;
            PE.Deal__c = true;
            PE.WOC_budget_allocation_kg__c = 2;
            PE.WOCInMarketValueHide__c = 0;
            PE.WOCConversionForcast__c = 0;                  
            PE.SOC_Total_budget_RMB__c = 0;
            PE.SOC_budget_allocation_kg__c = 0;
            PE.SOCInMarketValueHide__c = 0;
            PE.SOCConversionForcast__c = 0;                  
            PE.EOC_Total_budget_RMB__c = 0;
            PE.EOC_budget_allocation_kg__c = 0;
            PE.EOCInMarketValueHide__c = 0;
            PE.EOCConversionForcast__c = 0;            
            PE.NOC_Total_budget_RMB__c = 0;
            PE.NOC_budget_allocation_kg__c = 0;
            PE.NOCInMarketValueHide__c = 0;
            PE.NOCConversionForcast__c = 0;
            PE.Rate__c =2;
            PE.Total_Budget_Allocation_RMB__c = 1;
            insert PE;
            
            RegionalBudget__c RB = new RegionalBudget__c();
            RB.PESampleManagement__c = PE.id;
            RB.Approved__c = true;
            RB.ApprovalStatus__c = '审批通过';
            insert RB;
            
            Sub_Region_Budget__c SRB = new Sub_Region_Budget__c();
            SRB.PE_Sample_Management__c = PE.id;
            SRB.RegionalBudget__c = RB.id;
            SRB.Name = '2012年华南一区专业样品管理';
            insert SRB;
            
            test.setCurrentPageReference(Page.OverrideSubRegionBudgetNew);
            System.currentPageReference().getParameters().put('id', SRB.Id);          
            
            OverrideCityMonthlyBudget testCase = new OverrideCityMonthlyBudget();
            Profile pASM  = [select id from profile where name =: GlobalProperties.ProfileASM ];
            List<User> CH = [Select id,ManagerId From User Where profileId =: pASM.id  and IsActive =: true ];
            
            for(TableItemControl t : testCase.TableItemsDown){
                t.CB.CityHead__c = CH[0].id;  
            }            
            testCase.actionSupport();
            testCase.Submit();
            
            testCase.Save();
            testCase.Approve();
            testCase.Cancel();
        }    
    }
 
}